setfenv(1, require'winapi.oo')
require'winapi.oo.control'
require'winapi.listview'

ListView = class(Control)

function ListView:__init(info)
	self.window = CreateListView(update({}, info, {
							parent = info.parent and info.parent.window
						}))
	self.parent = info.parent
	if self.parent then
		self.parent.setnotify(self.window, function(...) return self:__notify(...) end)
	end
end

function ListView:__notify(h, WM, wParam, lParam, code)
	if code == LVN_GETDISPINFOW then
		local plvdi = ffi.cast('LPNMLVDISPINFOW', lParam)
		if self.get_item_data then
			self:get_item_data(LVITEMW(plvdi.item))
		end
	end
end

function ListView:addcolumn(pos, info)
	return ListView_InsertColumn(self.window, pos, info)
end

function ListView:additem(info)
	return ListView_InsertItem(self.window, info)
end

function ListView:setitem(info)
	return ListView_SetItem(self.window, info)
end

function ListView:getitem(info, item)
	return ListView_GetItem(self.window, item)
end

function ListView:delitem(pos)
	return ListView_DeleteItem(self.window, pos)
end

function ListView:clear()
	return ListView_DeleteAllItems(self.window)
end

--

if not ... then
require'winapi.oo.window'
local frame = Window()
local lv = ListView{parent = frame}
lv:addcolumn(1, {caption = 'name'})
lv:addcolumn(2, {caption = 'address'})
lv:additem({caption = 'you won\'t see me'})
lv:clear()
lv:additem({pos = 1, subitem = 1, caption = 'Louis Armstrong'})
lv:setitem({pos = 1, subitem = 2, caption = 'Basin Street'})
lv:additem({pos = 2, caption = 'Django Reinhardt'})
lv:additem({pos = 3, caption = LPSTR_TEXTCALLBACKW})
lv:additem({pos = 4, caption = LPSTR_TEXTCALLBACKW})
function lv:get_item_data(item)
	item.caption = 'n/a'
end
lv:delitem(3)
local item = LVITEMW{pos = 1, caption = 'xxxxxx'}
print(lv:getitem(item).lpszText)
frame:show()
MessageLoop()
end

